﻿using System;
using System.Collections.Generic;
using System.Collections;
using System.Text;
using System.IO;
using System.Xml.Serialization;
using System.Reflection;
using Microsoft.Win32;
using System.Runtime.InteropServices;
using System.Diagnostics;
using System.Security.AccessControl;
using System.Threading;
using System.Web;
using System.Net;
//using Microsoft.MediaCenter.UI;
using System.Windows.Forms;


namespace MediaPortal.Plugins
{

    public class Preferences
    {

        //[DllImport("kernel32.dll", SetLastError = true, CallingConvention = CallingConvention.Winapi)] 
        //[return: MarshalAs(UnmanagedType.Bool)] 
        //public static extern bool IsWow64Process([In] IntPtr hProcess, [Out] out bool lpSystemInfo);
        public string getBBC = "1", getITV = "0", getC4 = "0", getFive = "0", cacheLocation = "";
        public string bbc_alba = "1", bbc_scotland = "1", bbc_wales = "1", bbc_ireland = "1",bbc_radio="1";
        public string showEpisodes = "1", showList = "0";
        public string defaultCache = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData) + "\\Team MediaPortal\\MediaPortal\\iPlayer\\programList.dat";
        private string theFile;
        public string logFile = "log.dat";
        public double cacheInterval = 1000 * 60 * 60;
        public string installedDirectory;
        private string userAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0)";
        public string ignoreVersion = "";
        public DateTime remindDate = DateTime.Now.Date;
        public string getHulu = "1";
        public string defaultCountry = "UK";
        public string switchUKCommand = "";
        public string switchUSCommand = "";
        public string autoFavorites = "1";
        


        public Preferences()
        {
            theFile = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData) + "\\Team MediaPortal\\MediaPortal\\iPlayer\\preferences.xml";
        }

        public double getCacheInterval()
        {
            if (File.Exists(theFile))
            {
                loadPreferences("");
            }
            return cacheInterval;
        }

        public string getWebPage(string url)
        {
            string result = "";
            try
            {
                HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(url);
                myRequest.UserAgent = userAgent;
                myRequest.Method = "GET";
                myRequest.Timeout = 10000;
                CookieContainer c1 = new CookieContainer();
                myRequest.CookieContainer = c1;
                HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();
                StreamReader sr = new StreamReader(myResponse.GetResponseStream(), System.Text.Encoding.UTF8);
                result = sr.ReadToEnd();
                sr.Close();
            }
            catch (Exception e) {
                string s1 = e.ToString();

            }
            return result;
        }

        public string getLatestVersion()
        {
            string latestVersion = getWebPage("http://www.milliesoft.co.uk/current_version").Trim();
            return latestVersion;
        }


        public void loadPreferences(string overrideDirectory)
        {
            List<NameValuePair> thePrefs;
            if (File.Exists(theFile))
            {
                Stream fileStream = File.Open(theFile, FileMode.Open, FileAccess.Read, FileShare.Read);
                try
                {
                    XmlSerializer f1 = new XmlSerializer(typeof(List<NameValuePair>));
                    Object o1 = f1.Deserialize(fileStream);
                    thePrefs = (List<NameValuePair>)o1;
                    fileStream.Close();

                    thePrefs.ForEach(delegate(NameValuePair prefsPair)
                    {
                        if (prefsPair.name == "getBBC")
                        {
                            getBBC = prefsPair.value;
                        }
                        if (prefsPair.name == "getITV")
                        {
                            getITV = prefsPair.value;
                        }
                        if (prefsPair.name == "getC4")
                        {
                            getC4 = prefsPair.value;
                        }
                        if (prefsPair.name == "getFive")
                        {
                            getFive = prefsPair.value;
                        }
                        if (prefsPair.name == "cacheLocation")
                        {
                            cacheLocation = prefsPair.value;
                        }
                        if (prefsPair.name == "installedDirectory")
                        {
                            installedDirectory = prefsPair.value;
                        }
                        if (prefsPair.name == "bbc_alba")
                        {
                            bbc_alba = prefsPair.value;
                        }
                        if (prefsPair.name == "bbc_scotland")
                        {
                            bbc_scotland = prefsPair.value;
                        }
                        if (prefsPair.name == "bbc_wales")
                        {
                            bbc_wales = prefsPair.value;
                        }
                        if (prefsPair.name == "bbc_ireland")
                        {
                            bbc_ireland = prefsPair.value;
                        }
                        if (prefsPair.name == "bbc_radio")
                        {
                            bbc_ireland = prefsPair.value;
                        }
                        if (prefsPair.name == "getHulu")
                        {
                            getHulu = prefsPair.value;
                        }
                        if (prefsPair.name == "logFile")
                        {
                            logFile = prefsPair.value;
                        }
                        if (prefsPair.name == "cacheInterval")
                        {
                            cacheInterval = System.Convert.ToDouble(prefsPair.value);
                        }
                        if (prefsPair.name == "ignoreVersion")
                        {
                            ignoreVersion = prefsPair.value;
                        }
                        if (prefsPair.name == "remindDate")
                        {
                            remindDate = DateTime.Parse(prefsPair.value);
                        }
                        if (prefsPair.name == "defaultCountry")
                        {
                            defaultCountry = prefsPair.value;
                        }
                        if (prefsPair.name == "switchUKCommand")
                        {
                            switchUKCommand = prefsPair.value;
                        }
                        if (prefsPair.name == "switchUSCommand")
                        {
                            switchUSCommand = prefsPair.value;
                        }
                        if (prefsPair.name == "autoFavorites")
                        {
                            autoFavorites = prefsPair.value;
                        }
                    });

                }
                catch (Exception e) { }

                finally
                {
                    try { fileStream.Close(); }
                    catch (Exception e) { }
                }

            }
            else
            {
                cacheLocation = defaultCache;
            }
            Boolean save = false;  //my change
            if (cacheLocation == "" || cacheLocation == null)
            {
                cacheLocation = defaultCache;
                save = true;
            }
            if (overrideDirectory != "")
            {
                installedDirectory = "file://" + overrideDirectory + @"\";
                save = true;
            }
            else if (installedDirectory == "" || installedDirectory == null)
            {
                installedDirectory = "file://C:\\ProgramData\\Team MediaPortal\\MediaPortal\\iPlayer\\";
                
                if (File.Exists(@"C:\\Program Files\\Team MediaPortal\\MediaPortal\\MediaPortal.exe"))
                {
                    //IsWow64Process(Process.GetCurrentProcess().Handle, out is64);
                    //if (is64)
                    //{
                    installedDirectory = "file://C:\\Program Files\\Team MediaPortal\\MediaPortal\\iPlayer\\";
                }
                save = true;
            }
            if (installedDirectory.StartsWith("file:///"))
            {
                installedDirectory = "file://" + installedDirectory.Substring(8);
                save = true;
            }
            /* string AppRegKey = @"SOFTWARE\MillieSoft\TunerFreeMCE";
             using (RegistryKey preferencesKey = Registry.CurrentUser.OpenSubKey(AppRegKey))
             {
                 if (preferencesKey != null)
                 {
                     showEpisodes = (String)preferencesKey.GetValue(@"showEpisodes", "1");
                     showList = (String)preferencesKey.GetValue(@"showList", "0");
                 }
             }*/

            if (save)
            {
                savePreferences();
            }


        }

        public void setRegistryValue(string itemName, string itemValue)
        {
            try
            {
                string AppRegKey = @"SOFTWARE\MediaPortal\TunerFreeMP";
                using (RegistryKey preferencesKey = Registry.CurrentUser.OpenSubKey(AppRegKey, true))
                {
                    if (preferencesKey == null)
                    {
                        RegistryKey preferencesKey2 = Registry.CurrentUser.CreateSubKey(AppRegKey, RegistryKeyPermissionCheck.ReadWriteSubTree);
                        preferencesKey2.SetValue(itemName, itemValue, RegistryValueKind.String);
                        preferencesKey2.Close();

                    }
                    else
                    {
                        if ((String)preferencesKey.GetValue(itemName, "0") != itemValue)
                        {
                            preferencesKey.SetValue(itemName, itemValue, RegistryValueKind.String);
                        }
                    }
                    preferencesKey.Close();
                }
            }
            catch (Exception e) { }
        }

        public void savePreferences()
        {
            List<NameValuePair> list1 = new List<NameValuePair>();
            list1.Add(new NameValuePair("getBBC", getBBC));
            list1.Add(new NameValuePair("bbc_radio", bbc_radio));
            list1.Add(new NameValuePair("getITV", getITV));
            list1.Add(new NameValuePair("getC4", getC4));
            list1.Add(new NameValuePair("getFive", getFive));
            list1.Add(new NameValuePair("cacheLocation", cacheLocation));
            list1.Add(new NameValuePair("installedDirectory", installedDirectory));
            list1.Add(new NameValuePair("bbc_alba", bbc_alba));
            list1.Add(new NameValuePair("bbc_scotland", bbc_scotland));
            list1.Add(new NameValuePair("bbc_wales", bbc_wales));
            list1.Add(new NameValuePair("bbc_ireland", bbc_ireland));
            list1.Add(new NameValuePair("getHulu", getHulu));
            list1.Add(new NameValuePair("logFile", logFile));
            list1.Add(new NameValuePair("cacheInterval", cacheInterval.ToString()));
            list1.Add(new NameValuePair("ignoreVersion", ignoreVersion));
            list1.Add(new NameValuePair("remindDate", remindDate.ToShortDateString()));
            list1.Add(new NameValuePair("defaultCountry", defaultCountry));
            list1.Add(new NameValuePair("switchUKCommand", switchUKCommand));
            list1.Add(new NameValuePair("switchUSCommand", switchUSCommand));
            list1.Add(new NameValuePair("autoFavorites", autoFavorites));
            Stream fileStream = null;
            try
            {
                if (File.Exists(theFile))
                {
                    int attempts = 0;
                    while (attempts < 5)
                    {
                        try
                        {
                            fileStream = File.Open(theFile, FileMode.Create, FileAccess.Write, FileShare.Read);
                            attempts = 6;
                        }
                        catch (Exception e) { Thread.Sleep(1000); attempts++; }
                    }
                }
                else
                {
                    string theDir = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData) + "\\Team MediaPortal\\MediaPortal";
                    if (!Directory.Exists(theDir))
                    {
                        Directory.CreateDirectory(theDir);
                    }
                    theDir += "\\iPlayer";
                    if (!Directory.Exists(theDir))
                    {
                        Directory.CreateDirectory(theDir);
                    }
                    fileStream = File.Create(theFile);
                    FileSecurity fileSec = File.GetAccessControl(theFile);
                    fileSec.AddAccessRule(new FileSystemAccessRule("Users", FileSystemRights.FullControl, AccessControlType.Allow));
                    File.SetAccessControl(theFile, fileSec);
                }

                XmlSerializer f1 = new XmlSerializer(typeof(List<NameValuePair>));
                f1.Serialize(fileStream, list1);
            }
            finally
            {
                if (fileStream != null) { fileStream.Close(); }
            }

        }
        public string getCurrentVersion()
        {

            string s1 = "tony 1.0.0";
            return s1;
        }
        public string getCurrentVersionNumber()
        {

            //Assembly execAssembly = typeof(TunerFreeMP.MyAddIn).Assembly;

            //AssemblyName name = execAssembly.GetName();

            string s1 = "1.1.0";
            return s1;
        }

        public void LogToFile(string contents)
        {
            if (logFile != "")
            {
                //set up a filestream
                FileStream fs = new FileStream(logFile, FileMode.OpenOrCreate, FileAccess.Write);

                //set up a streamwriter for adding text

                StreamWriter sw = new StreamWriter(fs);

                //find the end of the underlying filestream

                sw.BaseStream.Seek(0, SeekOrigin.End);

                //add the text
                sw.WriteLine(contents);
                //add the text to the underlying filestream

                sw.Flush();
                //close the writer
                sw.Close();
            }
        }

        public void getLatestResolutions()
        {
            string resolutionFile = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData) + "\\Team MediaPortal\\MediaPortal\\iPlayer\\resolution.dat";
            DateTime lastWrite =  File.GetLastWriteTime(resolutionFile);
            if (lastWrite.AddDays(1) < DateTime.Now || !File.Exists(resolutionFile))
            {
                string resolutions = getWebPage("http://www.milliesoft.co.uk/resolution.dat?w=" + SystemInformation.PrimaryMonitorSize.Width+"&h="+SystemInformation.PrimaryMonitorSize.Height);
                if (resolutions.Length > 0)
                {

                    File.WriteAllText(resolutionFile, resolutions);

                }
            }
        }

        public string cleanString(string inStr)
        {
            return inStr.Replace("&apos;", "\'").Replace("&#039;", "\'").Replace("&amp;", "&").Replace("&nbsp;", " ").Replace("&rsquo;", "'").Trim();
        }

    }

    [Serializable]
    public class NameValuePair
    {
        public string name, value;
        public NameValuePair()
        {
        }
        public NameValuePair(string _name, string _value)
        {
            name = _name;
            value = _value;
        }
    }
}
